use axum::{
    Json,
    extract::{Json as ExtractJson, State},
    http::StatusCode,
    response::IntoResponse,
};
use std::sync::Arc;
use tracing::debug;

// use bc_base::PublicKeyHashBytes;

use crate::AppState;

// curl -X POST http://localhost:3000/api/balance \
//      -H "Content-Type: application/json" \
//      -d '{"account": "user123"}'
pub(crate) async fn query_balance(
    State(state): State<Arc<AppState>>,
    ExtractJson(body): ExtractJson<serde_json::Value>,
) -> impl IntoResponse {
    debug!("query_balance. body: {:?}", body);

    // let account = match body.get("account") {
    //     Some(account) => {
    //         let acc = account.as_str().unwrap_or_default();
    //         let acc = PublicKeyHashBytes::from_hex_str(acc);
    //         match acc {
    //             Ok(acc) => acc,
    //             Err(e) => {
    //                 warn!("[{}] The account should be HEX string.", e);
    //                 return (
    //                     StatusCode::BAD_REQUEST,
    //                     Json(serde_json::json!({"error": "Invalid account format"})),
    //                 );
    //             }
    //         }
    //     }
    //     None => {
    //         return (
    //             StatusCode::BAD_REQUEST,
    //             Json(serde_json::json!({"error": "Account is required"})),
    //         );
    //     }
    // };

    let mng = state.bc_manager.lock().await;
    let balance = mng.query_balance().await;
    // debug!(
    //     "Query balance for account: {}. Balance: {:?}",
    //     account, balance
    // );
    (
        StatusCode::OK,
        Json(serde_json::json!({ "balance": balance })),
    )
    // match r {
    //     Ok(balance) => {
    //         debug!(
    //             "Query balance for account: {}. Balance: {:?}",
    //             account, balance
    //         );
    //         (
    //             StatusCode::OK,
    //             Json(serde_json::json!({ "balance": balance })),
    //         )
    //     }
    //     Err(e) => {
    //         warn!("[{}] Failed to query balance.", e);
    //         (
    //             StatusCode::NOT_FOUND,
    //             Json(serde_json::json!({"error": "Account not found"})),
    //         )
    //     }
    // }
}
